package com.atguigu.tingshu.live.service.impl;

import com.atguigu.tingshu.live.mapper.LiveRoomMapper;
import com.atguigu.tingshu.live.service.LiveRoomService;
import com.atguigu.tingshu.live.util.LiveAutoAddressUtil;
import com.atguigu.tingshu.model.live.LiveRoom;
import com.atguigu.tingshu.vo.live.LiveRoomVo;
import com.atguigu.tingshu.vo.live.TencentLiveAddressVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class LiveRoomServiceImpl extends ServiceImpl<LiveRoomMapper, LiveRoom> implements LiveRoomService {

	@Autowired
	private LiveRoomMapper liveRoomMapper;

	@Override
	public LiveRoom saveLiveRoom(LiveRoomVo liveRoomVo, Long userId) {
		//	如果这个用户有一个正在直播的直播间，则不能创建! --->

		//	创建对象
		LiveRoom liveRoom = new LiveRoom();
		//	先属性拷贝：
		BeanUtils.copyProperties(liveRoomVo,liveRoom);
		liveRoom.setUserId(userId);
		//	状态 默认是直播中...
		liveRoom.setStatus("1");
		//	appName
		liveRoom.setAppName("live");
		//	stream_name
		liveRoom.setStreamName("guigu"+userId);
		//	设置过期时间
		Long txTime = liveRoom.getExpireTime().getTime()/1000;
		//	赋值推流、拉流地址
		TencentLiveAddressVo tencentLiveAddressVo = LiveAutoAddressUtil.getAddressUrl(liveRoom.getStreamName(), txTime);
		liveRoom.setPushUrl(tencentLiveAddressVo.getPushWebRtcUrl());
		liveRoom.setPlayUrl(tencentLiveAddressVo.getPullWebRtcUrl());
		//	保存数据
		liveRoomMapper.insert(liveRoom);
		//	返回数据
		return liveRoom;
	}

	@Override
	public LiveRoom getCurrentLive(Long userId) {
		//	获取数据 判断这个直播间是否结束。
		return liveRoomMapper.selectOne(new LambdaQueryWrapper<LiveRoom>().eq(LiveRoom::getUserId,userId).ge(LiveRoom::getExpireTime,new Date()));
	}
}
